package cn.zc.student.service.config;



import cn.zc.student.service.config.handler.StudentExceptionHandler;
import cn.zc.tools.security.filter.StudentSecurityFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @author: e
 * @date: 2021/12/23
 * @description: 预留安全策略配置，方便后续老大要做权限类分类
 */

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private StudentExceptionHandler studentExceptionHandler;



    @Resource
    private StudentSecurityFilter securityFilter;

    //注入一个密码加密器
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }





    //安全策略
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()                       //关闭csrf跨域
                .exceptionHandling().accessDeniedHandler(studentExceptionHandler)
                .and()
                .authorizeRequests()
                .antMatchers("/**").permitAll()
                .antMatchers("/student/studentPasswordLogin").permitAll()
                .antMatchers("/student/test").hasAnyRole("admin")
                .antMatchers(HttpMethod.OPTIONS,"/**").anonymous()    //允许浏览器发送options请求检测
                .anyRequest().authenticated()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)   //设定session为无状态模式，我们这里采用token
                .and()
                .addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter.class);   //设定自定义拦截器，并加载自带的filter

        http.headers().cacheControl();  //禁用缓存
    }
}
